//
//  RSLocationManager.m
//  StaffTax
//
//  Created by 侯伟 on 2021/3/4.
//  Copyright © 2021 侯伟. All rights reserved.
//

#import "RSLocationManager.h"

@interface RSLocationManager ()<CLLocationManagerDelegate>{
    CLLocationManager *_locationManager;
}


@end

@implementation RSLocationManager

+ (instancetype)sharedInstance{
    
    static id sharedInstance = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[RSLocationManager alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init{
    self = [super init];
    if (self){
        [self initData];
        [self setupLocationManager];
    }
    
    return self;
}

- (void)initData{
    _isLocation = NO;
    _distanceFilter = 50;
    _pausesLocationUpdatesAutomatically = NO;
    _desiredAccuracy = kCLLocationAccuracyBest;
    _allowsBackgroundLocationUpdates = NO;
    
}

-(void)setupLocationManager{
    
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.distanceFilter = self.distanceFilter;
    _locationManager.pausesLocationUpdatesAutomatically = self.pausesLocationUpdatesAutomatically;
    _locationManager.desiredAccuracy = self.desiredAccuracy;
    _locationManager.allowsBackgroundLocationUpdates = self.allowsBackgroundLocationUpdates;
    
    [self startUpdatingHeading];
}


- (void)setDistanceFilter:(NSInteger)distanceFilter{
    _distanceFilter = distanceFilter;
    _locationManager.distanceFilter = distanceFilter;
}

- (void)setPausesLocationUpdatesAutomatically:(BOOL)pausesLocationUpdatesAutomatically{
    _pausesLocationUpdatesAutomatically = pausesLocationUpdatesAutomatically;
    _locationManager.pausesLocationUpdatesAutomatically = pausesLocationUpdatesAutomatically;
}

- (void)setDesiredAccuracy:(CLLocationAccuracy)desiredAccuracy{
    _desiredAccuracy = desiredAccuracy;
    _locationManager.desiredAccuracy =desiredAccuracy;
}

- (void)setAllowsBackgroundLocationUpdates:(BOOL)allowsBackgroundLocationUpdates{
    _allowsBackgroundLocationUpdates = allowsBackgroundLocationUpdates;
    _locationManager.allowsBackgroundLocationUpdates = allowsBackgroundLocationUpdates;
}


#pragma mark 开始定位
- (void)startUpdatingLocation{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    switch (status) {
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:{
            [self showAlertViewController];
            return;
        }
            break;
        default:
            break;
    }
    
    [_locationManager startUpdatingLocation];
    _isLocation = YES;
}

#pragma mark 结束定位
- (void)stopUpdatingLocation{
    [_locationManager stopUpdatingLocation];
    _isLocation = NO;
}

/**
 *  @brief 开始获取设备朝向，如果设备支持方向识别，则会通过代理回调方法
 */
- (void)startUpdatingHeading{
    
    [_locationManager startUpdatingHeading];
}

/**
 *  @brief 停止获取设备朝向
 */
- (void)stopUpdatingHeading{
    [_locationManager stopUpdatingHeading];
}

#pragma mark - 警示弹框

- (BOOL)isAlert{
    return self.alertViewController ? YES:NO;
}

- (UIViewController*)alertViewController{
    return objc_getAssociatedObject(self,@selector(alertViewController));
}

- (void)setAlertViewController:(UIViewController *)alertViewController{
    objc_setAssociatedObject(self, @selector(alertViewController),alertViewController , OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)showAlertViewController{
    
    if(self.isAlert) return ;
    
    NSString *content = [NSString stringWithFormat:@"【%@】的定位权限已被禁用。\n请在设备的【设置】->【隐私】->【定位服务】中开启定位服务权限", [HApp name]];
    
    UIViewController* alert = [Alert confirmChange:@"定位权限禁用提醒" message:content confirmTitle:@"设置" cancelTitle:@"取消" completion:^(BOOL Bool) {
        [self setAlertViewController:NULL];
        if(Bool){
            NSURL* url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if([[UIApplication sharedApplication] canOpenURL:url]){
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:NULL];
                } else {
                    [[UIApplication sharedApplication] openURL:url];
                }
            }
        }
    }];
    [self setAlertViewController:alert];
}

- (void)hiddenAlertViewController{

    UIViewController* alert = [self alertViewController];
    if(!alert) return;
    
    [alert dismissViewControllerAnimated:YES completion:NULL];
    [self setAlertViewController:NULL];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *location = [locations lastObject];

    if(self.delegate && [self.delegate respondsToSelector:@selector(locationManager:didUpdateLocation:)]){
        [self.delegate locationManager:self didUpdateLocation:location];
    }
    
    if(self.locationChangedBlock){
        self.locationChangedBlock(location, NULL);
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if(self.delegate && [self.delegate respondsToSelector:@selector(locationManager:didUpdateLocationFailed:)]){
        [self.delegate locationManager:self didUpdateLocationFailed:error];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    _authStatus = status;
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:{
            [manager requestWhenInUseAuthorization];
        }
            break;
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:{
            [self showAlertViewController];
        }
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:{
            [self hiddenAlertViewController];
            [self startUpdatingLocation];
        }
        default:
            break;
    }
    
    if(self.delegate&& [self.delegate respondsToSelector:@selector(locationManager:didChangeAuthorizationStatus:)]){
        [self.delegate locationManager:self didChangeAuthorizationStatus:status];
    }
}
@end
